<template>
    <el-dialog title="试题" v-model="visible" width="100%"
      :close-on-click-modal="false" draggable>
        <el-container>
            <el-main>
                <el-card style="margin: 0 10px 20px 20px">
                    <el-form ref="dataFormRef" :model="form" formDialogRef label-width="90px" v-loading="loading">
                        <el-row :gutter="24">
                            <el-col :span="20" class="mb20">
                                <el-form-item label="题干" prop="stem" :rules="[{ required: true, message: '请输入题干',trigger: 'change',}]" >
                                    <el-input placeholder="请输入题干" v-model="form.stem" clearable   size="medium"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="9" class="mb20" style="margin-top: 10px">
                                <el-form-item label="题型" prop="questionType" :rules="[{ required: true, message: '请选择题型',trigger: 'change',}]">
                                    <el-select v-model="form.questionType" placeholder="请选择题型" filterable clearable style="width: 200px">
                                        <el-option :label="item.label" :value="item.value" v-for="(item, index) in tkgl_topic_type" :key="index"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="9" class="mb20"  style="margin-top: 10px">
                                <el-form-item label="难易程度" style="width: 300px" prop="difficulty" :rules="[{ required: true, message: '请选择题难度',trigger: 'change',}]">
                                    <el-input-number v-model="form.difficulty" :min="1" :max="100"  />
                                </el-form-item>
                            </el-col>
                            <!-- 单选 -->
                            <el-col :span="15" class="mb20"  v-if="form.questionType == 'radio'">
                                <!--   A    -->
                                <div class="option">
                                    <el-form-item label="A" prop="optionA" :rules="[{ required: true, message: '请输入',trigger: 'change',}]">
                                        <el-input placeholder="请输入" v-model="form.optionA" clearable />
                                    </el-form-item>
                                    <el-form-item  prop="answer" class="answer">
                                        <el-radio v-model="form.answer" label="A">设为正确答案</el-radio>
                                    </el-form-item>
                                </div>
                                <!--   B  -->
                                <div class="option">
                                    <el-form-item label="B" prop="optionB" :rules="[{ required: true, message: '请输入',trigger: 'change',}]">
                                        <el-input placeholder="请输入" v-model="form.optionB" clearable />
                                    </el-form-item>
                                    <el-form-item  prop="answer" class="answer">
                                        <el-radio v-model="form.answer" label="B">设为正确答案</el-radio>
                                    </el-form-item>
                                </div>
                                <!--   C  -->
                                <div class="option">
                                    <el-form-item label="C" prop="optionC" :rules="[{ required: true, message: '请输入',trigger: 'change',}]">
                                        <el-input placeholder="请输入" v-model="form.optionC" clearable />
                                    </el-form-item>
                                    <el-form-item  prop="answer" class="answer">
                                        <el-radio v-model="form.answer" label="C">设为正确答案</el-radio>
                                    </el-form-item>
                                </div>
                                <!--  D  -->
                                <div class="option">
                                    <el-form-item label="D" prop="optionD" :rules="[{ required: true, message: '请输入',trigger: 'change',}]">
                                        <el-input placeholder="请输入" v-model="form.optionD" clearable />
                                    </el-form-item>
                                    <el-form-item  prop="answer" class="answer">
                                        <el-radio v-model="form.answer" label="D">设为正确答案</el-radio>
                                    </el-form-item>
                                </div>
                            </el-col>
                            <!-- 多选 -->
                            <el-col :span="24" class="mb20" v-else-if="form.questionType == 'multi'">
                                <!--   A    -->
                                <div class="option">
                                    <el-form-item label="A" prop="optionA" :rules="[{ required: true, message: '请输入',trigger: 'change',}]">
                                        <el-input placeholder="请输入" v-model="form.optionA" clearable />
                                    </el-form-item>
                                    <el-form-item  prop="answer" class="answer">
                                        <el-checkbox v-model="answer" label="A" size="large">设为正确答案</el-checkbox>
                                    </el-form-item>
                                </div>
                                <!--   B  -->
                                <div class="option">
                                    <el-form-item label="B" prop="optionB" :rules="[{ required: true, message: '请输入',trigger: 'change',}]">
                                        <el-input placeholder="请输入" v-model="form.optionB" clearable />
                                    </el-form-item>
                                    <el-form-item  prop="answer" class="answer">
                                        <el-checkbox v-model="answer" label="B" size="large">设为正确答案</el-checkbox>
                                    </el-form-item>
                                </div>
                                <!--   C  -->
                                <div class="option">
                                    <el-form-item label="C" prop="optionC" :rules="[{ required: true, message: '请输入',trigger: 'change',}]">
                                        <el-input placeholder="请输入" v-model="form.optionC" clearable />
                                    </el-form-item>
                                    <el-form-item  prop="answer" class="answer">
                                        <el-checkbox v-model="answer" label="C" size="large">设为正确答案</el-checkbox>
                                    </el-form-item>
                                </div>
                                <!--  D  -->
                                <div class="option">
                                    <el-form-item label="D" prop="optionD" :rules="[{ required: true, message: '请输入',trigger: 'change',}]">
                                        <el-input placeholder="请输入" v-model="form.optionD" clearable />
                                    </el-form-item>
                                    <el-form-item  prop="answer" class="answer">
                                        <el-checkbox v-model="answer" label="D" size="large">设为正确答案</el-checkbox>
                                    </el-form-item>
                                </div>
                            </el-col>
                            <!-- 填空 -->
                            <el-col :span="24" class="mb20" v-else-if="form.questionType == 'fill'">
                                <el-form-item label="答案" prop="answer" :rules="[{ required: true, message: '请输入',trigger: 'change',}]">
                                    <el-input placeholder="请输入答案" v-model="form.answer" clearable />
                                </el-form-item>
                            </el-col>
                            <!-- 判断 -->
                            <el-col :span="24" class="mb20" v-else-if="form.questionType =='judge'">
                                <el-form-item label="答案"  prop="answer" :rules="[{ required: true, message: '请判断',trigger: 'change',}]">
                                    <el-radio-group v-model="form.answer" class="ml-4">
                                        <el-radio label="对" size="large">对</el-radio>
                                        <el-radio label="错" size="large">错</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                            <!-- 简答 -->
                            <el-col :span="24" class="mb20" v-else-if="form.questionType == 'answer'" >
                                <el-form-item label="答案" prop="answer" :rules="[{ required: true, message: '请输入',trigger: 'change',}]">
                                    <el-input placeholder="请输入答案" v-model="form.answer" clearable type="textarea" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="20" class="mb20" style="margin: 10px 0">
                                <el-text style="margin-left: 50px">解析</el-text>
                                <el-form-item label="" prop="readouts">
                                    <el-input  v-model="form.readouts"  clearable maxlength="600" type="textarea"/>
                                </el-form-item>
                                <el-button type="primary" style="margin-left: 600px;margin-top: 10px" @click="getAddQuestion">创建</el-button>
                            </el-col>
                        </el-row>
                    </el-form>
                </el-card>
                <el-card style="margin: 0 10px 20px 20px">
                    <el-text>添加试题</el-text>
                    <div class="line"></div>
                    <el-table :data="dataList" v-loading="dataListLoading" style="width: 100%"  height='150'  tooltip-effect="dark">
                        <el-table-column type="index" label="试题" width="80" show-overflow-tooltip />
                        <el-table-column prop="stem" label="题干" width="150" show-overflow-tooltip/>
                        <el-table-column prop="questionType" label="题型"  width="150" show-overflow-tooltip>
                            <template #default="scope">
                                <dict-tag :options="tkgl_topic_type" :value="scope.row.questionType"></dict-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="fileNameAll" label="关联资料"  show-overflow-tooltip/>
                        <el-table-column prop="readouts" label="解析" show-overflow-tooltip/>
                        <el-table-column prop="answer" label="答案" width="120" show-overflow-tooltip/>
                    </el-table>
                    <div class="avue-crud__pagination">
                        <el-pagination
                                @size-change="sizeChangeHandle"
                                @current-change="currentChangeHandle"
                                :current-page="pageIndex"
                                :page-sizes="[5, 10, 15]"
                                :page-size="pageSize"
                                :total="totalPage"
                                background
                                layout="total, sizes, prev, pager, next, jumper"
                        >
                        </el-pagination>
                    </div>
                </el-card>
            </el-main>
            <el-aside width="700px">
                <el-card style="margin: 0 10px 20px 0px;height: 100%">
                    <div class="canvas" style="height: 650px">
                        <iframe  frameborder="0" :src="allUrl" style="width: 100%; height: 100%"></iframe>
                    </div>
                </el-card>
            </el-aside>
        </el-container>
    </el-dialog>
</template>

<script setup lang="ts" name="KszlFileDialog">
import { useDict } from '/@/hooks/dict';
import { useMessage } from "/@/hooks/message";
import {getObj, addObj, putObj, office, officeView} from '/@/api/train/kszlFile'
import { rule } from '/@/utils/validate';
import {ref} from "vue";
import {addtkglQuestionList, fetchList} from "/@/api/train/kszlTestQuestion";
import { ElMessage } from 'element-plus'
const emit = defineEmits(['refresh']);
// 定义变量内容
const dataFormRef = ref();
const visible = ref(false)
const loading = ref(false)
const officeUrl = ref()
const random = ref()
const type = ref()
const officeUrl1 = ref()
const allUrl = ref()
const dataListLoading = ref(false);
const dataList = ref<any[]>([]); // 根据你的数据结构来定义类型
const totalPage = ref(0);
const pageIndex = ref(1); // 假设第一页是1
const pageSize = ref(5); // 假设每页显示5条数据
const answer = ref(['A'])
// 定义字典
const { tkgl_topic_type } = useDict('tkgl_topic_type')
// 提交表单数据
const form = reactive({
    difficulty:1
});
const receivingList = reactive({});
// 定义校验规则
const dataRules = ref({})
onMounted(()=>{
    office().then((res)=>{
        officeUrl.value = res.data
    })
    officeView().then((res)=>{
        officeUrl1.value = res.data
    })
})
// 打开弹窗
const openDialog = (queryForm:any,row: any) => {
    type.value = row.fileName
    // console.log('弹框',row)
    visible.value = true
    let originalUrl = `${officeUrl.value}/downloadFilec?id=${row.onlyOfficeId}`;
    let previewUrl  = originalUrl +  `&fullfilename=${row.id}${type.value}`
    // console.log('previewUrl',previewUrl)
    //转换为 Base64 编码
    let base64EncodedUrl = btoa(previewUrl);
    //使用 encodeURIComponent 编码
    let encodedUrl = encodeURIComponent(base64EncodedUrl);
    allUrl.value = officeUrl1.value + encodedUrl
    // console.log(allUrl.value,receivingList, "jhsjhd")
    receivingList.relatedInfo　=　row.fileAddress
    receivingList.fileNameAll　=　row.fileNameView
    receivingList.partPostId = queryForm.studyPostIds
    receivingList.zymcId = queryForm.majorNameIds
    receivingList.keyId = queryForm.keyPointIds
    if(queryForm.state == '0')
    {
        receivingList.partOrgId = queryForm.studyGroupIds.join('/')
        receivingList.partOrgName=  queryForm.studyGroupNames.join('/')
        receivingList.partPostName= queryForm.studyPosts
        receivingList.zymcName= queryForm.majorNames
        receivingList.keyPoint= queryForm.keyPoints
    }else {
        receivingList.partOrgId = queryForm.partOrgId
        receivingList.partOrgName = queryForm.partOrgName
        receivingList.partPostName = queryForm.studyPosts
        receivingList.zymcName = queryForm.majorNames
        receivingList.keyPoint = queryForm.keyPoints
    }
    receivingList.fileId = row.onlyOfficeId
    delete receivingList.id
    // console.log('---------',receivingList)
    getList()
};
const getAddQuestion = () =>{
    let arr = Object.assign({},receivingList,form)
    if(form.questionType == 'multi')
    {
        arr.answer = answer.value.join('')
    }
    // console.log('--------',arr)
    addtkglQuestionList(arr).then((res)=>{
        // console.log('res-----',res.msg)
    }).catch(error=>{
        if(error.code == 1){
            ElMessage({
                showClose: true,
                message: '该试题已重复',
                type: 'warning',
            })
        }
    })
    setTimeout(() => {
        getList()
    }, 2000);
    // 重置表单数据
    nextTick(() => {
    	dataFormRef.value?.resetFields();
    });
}
const getList = async () =>{
    dataListLoading.value = true;
    try {
        const response = await fetchList({
            fileId: receivingList.fileId,
            current: pageIndex.value,
            size: pageSize.value
        });
        dataList.value = response.data.records;
        totalPage.value = response.data.total;
    } catch (error) {
        console.error('Error fetching data:', error);
        // 在这里处理错误，例如显示错误消息给用户
    } finally {
        dataListLoading.value = false;
    }
}
// 每页数
const  sizeChangeHandle = (val:number)=> {
    pageSize.value = val
    pageIndex.value = 1
    getList()
}
// 当前页
const  currentChangeHandle =(val:number)=> {
    pageIndex.value = val
    getList()
}
// 提交
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	try {
    loading.value = true;
		form.id ? await putObj(form) : await addObj(form);
		useMessage().success(form.id ? '修改成功' : '添加成功');
		visible.value = false;
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
    loading.value = false;
  }
};
// 初始化表单数据
const getkszlFileData = (id: string) => {
  // 获取数据
  loading.value = true
  getObj(id).then((res: any) => {
    Object.assign(form, res.data)
  }).finally(() => {
    loading.value = false
  })
};
// 暴露变量
defineExpose({
  openDialog
});
</script>
<style lang="scss" scoped>
    .el-form{
        margin-left: 15px;
    }
    .option{
        display: flex;
    }
    .answer{
        margin: -15px 0 0 30px
    }
    .line{
        border-top: 1px dashed #817B7B;
        width: 1270px;
        height: 0;
        margin-top: 10px;
        margin-left: -5px
    }
    .el-main{
        --el-main-padding: 0px !important;
    }
    .el-container{
        margin-top: -20px;
    }
    .mb20 {
         margin-bottom: 5px !important;
    }
</style>